<template>
  <div>
    <micro-app
      name="ali-designer"
      :url="url"
      baseroute=""
      :data="microAppData"
      @created="handleCreate"
      @beforemount="handleBeforeMount"
      @mounted="handleMount"
      @unmount="handleUnmount"
      @error="handleError"
      @datachange="handleDataChange"
      disable-sandbox
    />
  </div>
</template>

<script>
import microApp from '@micro-zoe/micro-app'

export default {
  name: 'PageDesign',
  props: {
    id: { type: String, default: '' },
  },
  data() {
    return {
      url: `http://localhost:8360`,
      microAppData: { scenarioId: this.id },
    }
  },
  created() {
    microApp.setGlobalData({ token: this.$store.getters.token })
  },
  mounted() {
    this.init()
  },
  methods: {
    async init() {
      const res = await this.$request({
        url: '/lowcode/getDataBySql',
        method: 'post',
        data: { sqlid: '页面信息', where: `scenarioId='${this.id}'` },
      })
      const { scenarioName } = res.list[0]
      microApp.setGlobalData({ scenarioName })

      const path = `/dev-platform/pagedesign/${this.id}`
      const title = '页面设计-' + scenarioName
      this.$store.commit('tagsView/UPDATE_VISITED_VIEW_TITLE', { path, title })
    },
    handleDataChange(e) {
      const { action, params } = e.detail.data
      // console.log('收到ali-designer的数据:', action, params)

      const invokes = {
        navToPreview: (p) => {
          console.log('call navToPreview', p)
          this.$router.push({ name: 'PagePreview', params: { id: this.id } })
        },
      }

      invokes[action](params)
    },

    handleCreate() {
      // console.log('ali-designer 创建了')
    },

    handleBeforeMount() {
      // console.log('ali-designer 即将被渲染')
    },

    handleMount() {
      // console.log('ali-designer 已经渲染完成')
      // setTimeout(() => {
      //   this.microAppData = { msg: '来自基座的新数据' }
      // }, 2000)
    },

    handleUnmount() {
      // console.log('ali-designer 卸载了')
    },

    handleError() {
      // console.log('ali-designer 加载出错了')
    },
  },
}
</script>
<style></style>
